MyDesktop.PartWindow = Ext.extend(Ext.app.Module, {
    id:'part-win',
    init : function(){
        this.launcher = {
            text: '配件管理',
            iconCls:'icon-grid',
            handler : this.createWindow,
            scope: this
        }
    },
    partRecord : Ext.data.Record.create([
	    {name : 'id',mapping : 'id',type : 'int'}, 
	    {name : 'name',mapping : 'name',type : 'string'}, 
	    {name : 'pinyin',mapping : 'namePinyin',type : 'string'},
	    {name : 'unit',mapping : 'unit',type : 'string'},
	    {name : 'brand',mapping : 'brand',type : 'string'},
	    {name : 'unitPrice',mapping : 'unitPrice',type : 'string'}
	   ]),
	cm_part : new Ext.grid.ColumnModel([
	       new Ext.grid.RowNumberer(),
	       {header : '品牌名称',width : 120,dataIndex : 'brand'},
		   {header : '配件名称',width : 120,dataIndex : 'name'},
		   {header : '单价',width : 40,dataIndex : 'unitPrice'},
		   {header : '单位',width : 40,dataIndex : 'unit'}
	]),
	
	getPanel:function(){
		 	 var store=new Ext.data.Store({
				 url : app.url+'/admin/partList.do',
				 baseParams:{start:0,limit:20},
				 autoLoad : true,
                 reader: new Ext.data.JsonReader({totalProperty : 'totalProperty',root : 'root'}, this.partRecord)
             });	
       		 
             var partCombox = getPartCombox('');
       		 var part_detailForm =new Ext.FormPanel({
                		border : true,
						region: 'north',
                		labelAlign : 'right',
                		labelWidth :30,
						frame : true,
						height: 45,
                		items : [{// 1 row
									layout:'column',
									items:[{
			                              xtype:'hidden',
			                              name:'id'
			                        },{
        								columnWidth : .28,
        								layout : 'form',
        								items : [{xtype : 'textfield',fieldLabel : '品牌',name : 'brand',anchor : '100%',enableKeyEvents : true,allowBlank : false, minLength : 2, maxLength : 30}]
								    },{
        								columnWidth : .36,
        								layout : 'form',
										labelWidth : 40,
        								items : [{xtype : 'textfield',fieldLabel : '名称',name : 'name',anchor : '100%',allowBlank : false, minLength : 2,maxLength : 30}]
								    },{
        								columnWidth : .18,
        								layout : 'form',
										labelWidth : 30,
        								items : [{xtype : 'numberfield',fieldLabel : '单价',name : 'unitPrice',anchor : '100%',enableKeyEvents : true,allowBlank : false}]
								    },{
        								columnWidth : .18,
        								layout : 'form',
										labelWidth : 30,
        								items : [getUnitCombo()]
								    }]
							}]
						});
		var partPackageRecord= Ext.data.Record.create([
        	{name : 'partId'}, 
        	{name : 'amount'},
			{name : 'unitPrice'}
    	]);	 
		var tb_partPackage_add = new Ext.Toolbar({
                items: [{
                	 xtype: 'button',
                     text: '增加',
        			 iconCls: 'add',
        			 handler : function(){
        			  var r=new partPackageRecord({});
        			  store_partPackage_new.add(r);
        			 }
                   
                  },'-',{
                	 xtype: 'button',
                     text: '删除',
        			 iconCls: 'remove',
        			 handler : function(){
        			   var record = grid_item.getSelectionModel().getSelected();
        		       if (record) {
        			     store_partPackage_new.remove(record);
        			     grid_item.getView().refresh();
        			   }
        			 }
                   
                  }]
         });
	var store_partPackage_new= new Ext.data.JsonStore({
	    root:'packageItems',
        fields: [
           {name: 'itemId',type:'int'},
           {name: 'amount', type: 'float'},
		   {name: 'unitPrice', type: 'float'}
        ]
     });	 
	 
	 var cm= new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(),
		 {header : '配件名称',width : 120,dataIndex : 'itemId',editor:partCombox,renderer: Ext.util.Format.comboRenderer(partCombox)},
		 {header : '数量',width : 90,dataIndex : 'amount',
		  editor:new Ext.form.NumberField({
		         allowBlank: false
		  })
		 },
		 {header : '单价',width : 90,dataIndex : 'unitPrice',
		  editor:new Ext.form.NumberField({
		         allowBlank: false
		  })
		 }

	 ]);		 
		 
		var grid_item = new Ext.grid.EditorGridPanel({
        	title : '零件打包条目',
        	iconCls : 'icon-grid',
        	collapsible: false,
			border:false,
            region: 'center',
            margins: '5 0 0 0',
			columnLines :true,
			autoScroll : true,
			width : 600,
			enableHdMenu : false,
        	viewConfig:
        	{
        	 forceFit:true,
        	 scrollOffset:15
        	 },	   	   
        	autoWidth : true,
        	region : 'center',
        	clicksToEdit:1,
			tbar : tb_partPackage_add,
        	cm : cm,
			ds : store_partPackage_new,
        	sm : new Ext.grid.CheckboxSelectionModel({singleSelect : false}),
        	enableColumnMove : false,
        	trackMouseOver : false,
        	frame : true
        	
        });		 
			 
       		 
       		 var addOrEditPart_win = new Ext.Window({
       		 	title:'安装信息录入',
                layout:'border',
                width:850,
                height:530,
				modal:true,
				closable: true,
				constrain:true,
                closeAction:'hide',
                plain: true,
				items : [part_detailForm,grid_item],
                buttonAlign : 'center',
                buttons: [{
                    text:'保存',
					iconCls : 'save',
					handler: submitForm
                },{
                    text: '取消',
					iconCls : 'close',
                    handler: function(){
                       addOrEditPart_win.hide();
                    }
                }]
       		 });
       		 
       		 var part_gridPanel =  new Ext.grid.GridPanel({					  
                        border:false,
						columnLines :true,
                        enableHdMenu : false,
						loadMask : {msg : '数据加载中...'},
                        ds: store,
                        cm: this.cm_part,						
                        viewConfig: {
                            forceFit:true
                        },
                        tbar:[{
                            text:'增加配件',
                            iconCls:'add',
                            handler:addPart
                        }, '-', {
                            text:'修改',
                            tooltip:'修改配件',
                            iconCls:'option',
                            handler:editPart
                        },'-',{
                            text:'删除',
                            tooltip:'删除配件',
                            iconCls:'delete'
                        }],
						bbar: new Ext.PagingToolbar({
                            pageSize: 20,
                            store: store,
                            displayInfo: true,
                            plugins: new Ext.ux.ProgressBarPager()
                        })
            });
                      
            
            
              //取得选中的记录
	 		function getSelectedItem(){
	     		var record= part_gridPanel.getSelectionModel().getSelected();	   
	     		if(record == null){
	        		 Ext.MessageBox.alert('提示','请选择要修改的明细！');
	         		return;
	     		}else{
	        		return record;
	     		}
	  		}
            
            function addPart(){
            	if(part_detailForm.form.el){
            		part_detailForm.form.el.dom.reset();            	
            	}else{
            		part_detailForm.form.reset();
            	}
				store_partPackage_new.removeAll();
		        addOrEditPart_win.isAdd = true;
		        addOrEditPart_win.setTitle("新增配件");
		        addOrEditPart_win.show();
            }
            
            function editPart(){
            	if(part_detailForm.form.el){
            		part_detailForm.form.el.dom.reset();            	
            	}else{
            		part_detailForm.form.reset();
            	}
				store_partPackage_new.removeAll();
            	var record=getSelectedItem();
            	if(record){
		    		addOrEditPart_win.setTitle("编辑配件");
		    		addOrEditPart_win.isAdd = false;
		    		//part_detailForm.getForm().loadRecord(record);
					
		    		addOrEditPart_win.show();
					loadFormData(record);
            	}else{
            		 Ext.MessageBox.alert('提示','请选择要修改的明细！');
            	}           	
            }
            
			var  loadFormData=function(record){
			     var form=part_detailForm.getForm();
			     form.load({
				     url:app.url+'/admin/partInfo.do?id='+record.get('id'),
				     waitMsg : '正在提载入数据...',
				     success:function(form, action){
	
					  store_partPackage_new.loadData(action.result.data);
					
	           		},
	           		failure:function(form, action){
	                	Ext.MessageBox.alert("提示","发生异常，请稍候处理!");    
	           		}
				 });
			
			 }
			

            function submitForm(){
			    var form=part_detailForm.getForm();
				var totalRecords =store_partPackage_new.getRange();
				var packageItem = [];
				for(var i=0;i<totalRecords.length;i++){
				   
				    packageItem.push(totalRecords[i].data);
				
				}
				//alert(Ext.encode(packageItem));
            	if(!form.isValid()){
	         		 return;
	      		}
	      		if(addOrEditPart_win.isAdd){
				   form.findField('id').setValue(0);
				  
	      		   	Ext.Ajax.request({
	           			url:app.url+'/admin/createPart.do',
	           			method :"post",
						jsonData :Ext.encode({part:form.getValues(),packageItems:packageItem}),
						waitMsg : '正在提交数据,请稍候...',
	          			success:function(response,options){
							store.reload();
							Ext.MessageBox.alert("提示","操作成功!");
							addOrEditPart_win.hide();
	           			},
	           			failure:function(response,options){
	                		Ext.MessageBox.alert("提示","发生异常，请稍候处理!");    
	           			}
	       			});
	      		}else{
            		Ext.Ajax.request({
	           			url:app.url+'/admin/updatePart.do',
	           			method :"post",
						jsonData :Ext.encode(form.getValues()),
						waitMsg : '正在提交数据,请稍候...',
	          			success:function(response,options){
							store.reload();
							Ext.MessageBox.alert("提示","修改成功!");
							addOrEditPart_win.hide();
	           			},
	           			failure:function(response,options){
	                		Ext.MessageBox.alert("提示","发生异常，请稍候处理!");    
	           			}
	       			});
           		}
         	}
         	
         	return part_gridPanel;
      },

    createWindow : function(){
        var desktop = this.app.getDesktop();
        var win = desktop.getWindow('part-win');
        if(!win){
            win = desktop.createWindow({
                id: 'brand-win',
                title:'配件管理',
                width:app.maxWidth,
                height:app.maxHeight,
                iconCls: 'icon-grid',
                shim:false,
                animCollapse:false,
                constrainHeader:true,
                layout: 'fit',
                items:this.getPanel()
            });
        }
        win.show();
    }
	
});
	 